// 调试函数
function debugLog(msg, data) {
    if (data === undefined) {
        node.warn(`DEBUG - ${msg}`);
    } else {
        node.warn(`DEBUG - ${msg}: ${JSON.stringify(data, null, 2)}`);
    }
}

try {
    // 验证输入数据
    if (!msg.payload || !msg.payload.data) {
        node.error("Invalid input data structure");
        return msg;
    }

    const inputData = msg.payload.data;
    const timestamp = msg.payload.timestamp;

    // 初始化结果对象
    const result = {
        timestamp: timestamp,
        data: {}
    };

    // 转换数据结构
    Object.entries(inputData).forEach(([pointId, pointData]) => {
        const dimensions = pointData.dimensions;
        
        // 处理每个维度
        Object.entries(dimensions).forEach(([dimensionKey, dimensionData]) => {
            const dimensionId = dimensionData.id;
            
            // 将数据直接存储在维度ID下
            result.data[dimensionId] = {
                ...dimensionData.stats,
                name: pointData.name,
                dimension: dimensionKey
            };
        });
    });

    // 设置输出消息
    msg.payload = result;
    debugLog('Transformation Result', {
        timestamp: result.timestamp,
        dimensionsProcessed: Object.keys(result.data).length
    });

} catch (error) {
    node.error("Error in MQTT transformation: " + error.message);
    node.warn(error.stack);
}

return msg; 